package com.tmall.testgen.plugin.wizards;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.tmall.testgen.client.ClientDataCenter;
import com.tmall.testgen.client.commond.SendCommond;
import com.tmall.testgen.client.commond.impl.SendCommondImpl;
import com.tmall.testgen.client.config.TargetProjectConfig;
import com.tmall.testgen.common.ConnectionCommond;
import com.tmall.testgen.common.bo.interact.back.syn.ConnectionSuccResult;
import com.tmall.testgen.common.util.SocketUtil;
import com.tmall.testgen.plugin.Activator;
import com.tmall.testgen.plugin.ConsoleFactory;
import com.tmall.testgen.plugin.wizards.runinspring.FileSelectionWizard;
import com.tmall.testgen.transfer.startor.TransferStartorForPlugin;

/**
 * The "New" wizard page allows setting the container for the new file as well
 * as the file name. The page will only accept file name without the extension
 * OR with the extension that matches the expected one (mpe).
 */

public class CreateTestCodeWizadPage extends WizardPage {
	private static String regex = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
	private Text ipText;
	// private Combo pidCombo;
	private org.eclipse.swt.widgets.List pidList;
	private Text testProjectWebAppPathText;

	public Set<String> local = new HashSet<String>();
	{
		local.add("localhost");
		local.add("127.0.0.1");
	}


	/**
	 * Constructor for SampleNewWizardPage.
	 * 
	 * @param pageName
	 */
	public CreateTestCodeWizadPage(ISelection selection) {
		super("wizardPage");
		setTitle("配置界面");
		setDescription("测试代码生成配置界面");
		//this.selection = selection;
	}

	/**
	 * @see IDialogPage#createControl(Composite)
	 */
	public void createControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		layout.numColumns = 5;
		layout.makeColumnsEqualWidth = false;
		container.setLayout(layout);

		// iPLabel
		Label iplabel = new Label(container, SWT.NONE);
		iplabel.setText("&IP:");
		GridData iplabelGd = new GridData(SWT.RIGHT, SWT.FILL, false, false, 1,1);
		iplabel.setLayoutData(iplabelGd);

		// ipText
		ipText = new Text(container, SWT.BORDER);
		GridData iptextGd = new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1);
		ipText.setLayoutData(iptextGd);
		ipText.setText("127.0.0.1");
		// ipText.addModifyListener(new ModifyListener() {
		// public void modifyText(ModifyEvent e) {
		// // ipChangeDeal();
		// }
		// });
		Button refreshJvmBtn = new Button(container, SWT.PUSH);
		refreshJvmBtn.setText("刷新虚拟机");
		GridData refreshJvmBtnGd = new GridData(SWT.RIGHT, SWT.FILL, false,false, 1, 1);
		refreshJvmBtn.setLayoutData(refreshJvmBtnGd);
		refreshJvmBtn.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				ipChangeDeal();
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				widgetSelected(arg0);
			}
		});

		// PID
		Label pidLabel = new Label(container, SWT.NONE);
		pidLabel.setText("虚拟机:");
		GridData pidlabelGd = new GridData(SWT.RIGHT, SWT.FILL, false, true, 1,3);
		pidLabel.setLayoutData(pidlabelGd);

		pidList = new org.eclipse.swt.widgets.List(container, SWT.BORDER| SWT.SINGLE | SWT.V_SCROLL);
		// pidText = new Text(container, SWT.BORDER);
		GridData textGd = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 3);
		// textGd.widthHint = 200;
		pidList.setLayoutData(textGd);
		pidList.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				pidList.setToolTipText(pidList.getSelection()[0]);
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				widgetSelected(arg0);
			}
		});


		// test class path label
		Label classPathlabel = new Label(container, SWT.NONE);
		classPathlabel.setText("测试工程WebApp:");
		GridData classPahtlabelGd = new GridData(SWT.RIGHT, SWT.FILL, false,false, 1, 1);
		classPathlabel.setLayoutData(classPahtlabelGd);

		// test class path Text
		testProjectWebAppPathText = new Text(container, SWT.BORDER | SWT.NONE);
		GridData testClassPathTextGd = new GridData(SWT.FILL, SWT.FILL, true,false, 3, 1);
		testProjectWebAppPathText.setLayoutData(testClassPathTextGd);

		if(Activator.getDefault().getConfig("WebAppInfo")!=null){
		    String webAppInfo=Activator.getDefault().getConfig("WebAppInfo");
		    String []infoes=webAppInfo.split("\\$");
		    if(infoes.length==3){
    		    String projectName=infoes[0];
                String projectLocation=infoes[1];
                String targetProjectWebAppPath= infoes[2];
                
                TargetProjectConfig.getInstance().setTargetProjectWebAppPath(projectName,projectLocation,targetProjectWebAppPath);
                TargetProjectConfig.getInstance().setTargetProjectConfigPath(targetProjectWebAppPath+"/web-inf/web.xml");
                
    			testProjectWebAppPathText.setText(targetProjectWebAppPath);
		    }
		}
		// class pach select
		Button classPathBth = new Button(container, SWT.PUSH);
		classPathBth.setText("浏 览");
		GridData classPathBthGd = new GridData(SWT.LEFT, SWT.FILL, false,false, 1, 1);
		classPathBth.setLayoutData(classPathBthGd);
		
		classPathBth.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				FileSelectionWizard wizard = new FileSelectionWizard(false);
				// WizardDialog dialog = new WizardDialog(getShell(), wizard);
				WizardDialog dialog = new WizardDialog(null, wizard);

				dialog.setPageSize(600, 400);
				dialog.create();
				int returnv = dialog.open();
				if (returnv == 0) {
					testProjectWebAppPathText.setText(wizard.getProjectPath());
					String projectName=wizard.getProject().getName();
					String projectLocation=wizard.getProject().getLocation().toString();
					String targetProjectWebAppPath= testProjectWebAppPathText.getText();
					
                    TargetProjectConfig.getInstance().setTargetProjectWebAppPath(projectName,projectLocation,targetProjectWebAppPath);
					TargetProjectConfig.getInstance().setTargetProjectConfigPath(targetProjectWebAppPath+"/web-inf/web.xml");
					
					Activator.getDefault().setConfig("WebAppInfo", projectName+"$"+projectLocation+"$"+targetProjectWebAppPath);
				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {

			}
		});

		// 拦截
		Label interceptlabel = new Label(container, SWT.NONE);
		interceptlabel.setText("&拦截表达式:");
		GridData interlabelGd = new GridData(SWT.RIGHT, SWT.TOP, false, false,1, 1);
		interceptlabel.setLayoutData(interlabelGd);

		GridData maxTextGd = new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1);
		maxTextGd.heightHint = 22;

		final Text interceptMethodsText = new Text(container, SWT.BORDER);
		interceptMethodsText.setLayoutData(maxTextGd);
		interceptMethodsText.addModifyListener(new ModifyListener() {
             public void modifyText(ModifyEvent e) {
                 ClientDataCenter.getInstance().setInterceptDes(interceptMethodsText.getText());
             }
         });
		
//		
//		Label mocklabel = new Label(container, SWT.NONE);
//		mocklabel.setText("&Mock表达式:");
//        GridData mockLabelGd = new GridData(SWT.RIGHT, SWT.TOP, false, false,1, 1);
//        mocklabel.setLayoutData(mockLabelGd);
//
//        GridData mockTextGd = new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1);
//        mockTextGd.heightHint = 22;
//
//        Text mockText = new Text(container, SWT.BORDER );
//        mockText.setLayoutData(mockTextGd);

		setControl(container);
	}
	private SendCommond sendCommond = new SendCommondImpl();

	private ConnectionSuccResult result;
	private String space = " ";

	/**
	 * 获取pid
	 * 
	 * @return
	 */
	private String getPid() {
		String pidStr = pidList.getSelection()[0];
		int index = pidStr.indexOf(space);
		pidStr = pidStr.substring(0, index);
		return  pidStr;
		
	}

	public boolean finish() throws Exception {
		String ip = ipText.getText();
		if(ip.trim().length()==0){
			MyMessageDialog.openWarnDialog(this.getShell(), "ip不可为空");
			return false;
		}
		String pid="";
		if( pidList.getSelection().length>0){
			pid = getPid();
		}
		if(pid.trim().length()==0){
			MyMessageDialog.openWarnDialog(this.getShell(), "请选择虚拟机");
			return false;
		}
		if(testProjectWebAppPathText.getText().trim().length()==0){
			MyMessageDialog.openWarnDialog(this.getShell(), "请选择测试工程WebApp");
			return false;
		}
		if(ClientDataCenter.getInstance().getInterceptDes()==null||ClientDataCenter.getInstance().getInterceptDes().length()==0){
		    MyMessageDialog.openWarnDialog(this.getShell(), "请填写拦截表达式");
            return false;
		}
		
		
		ClientDataCenter.getInstance().setIp(ip.trim());
		//ClientDataCenter.getInstance().setMockDes(mockDes.trim());
		ClientDataCenter.getInstance().setPid(pid.trim());
		
		
		 result = sendCommond.tryAttatch(ip, pid);
		 ClientDataCenter.getInstance().setDbInfos(result.getDbInfos());
		 ClientDataCenter.getInstance().setStart(true);
		 
		 return true;
		//result = getTest();
	}


	public ConnectionSuccResult getResult() {
		return result;
	}

	public void setResult(ConnectionSuccResult result) {
		this.result = result;
	}

	/**
	 * ip文本输入处理
	 */
	private void ipChangeDeal() {
		String ipStr = ipText.getText();
		
		pidList.setItems(new String[] {});
		if (ipStr == null || ipStr.trim().length() == 0) {
			return;
		}
		
		if (ipStr.matches(regex)) {
			// 符合ip规范
			String[] ipItem = getJVMPid(ipStr);
			pidList.setItems(ipItem);
		}

	}

	private String[] getShowName(Map<String, String> map) {
		String[] result = new String[map.keySet().size()];
		int i = 0;
		for (String pid : map.keySet()) {
			result[i++] = pid + " " + map.get(pid);
		}
		return result;
	}

	private String[] getJVMPid(String ip) {
	    
	    try {
	        
	        if(local.contains(ip)){
	            if(SocketUtil.isPortAvailable(ConnectionCommond.Transfer_Server_Port)){
	                String transferJarPath=Platform.getInstallLocation().getURL().getPath()+"plugins/testgen";
	               TransferStartorForPlugin.runCmd(transferJarPath);
	            }
	            
	        }
            return getShowName(sendCommond.getRemoteVMs(ip));
        } catch (Exception e) {
            MyMessageDialog.openWarnDialog(this.getShell(), "虚拟机列表获取错误，请查看控制台的异常信息");
            
            ConsoleFactory.putError(e);

            return null;
        }
	   
	}
	

}